package cn.iocoder.yudao.module.ao.controller.admin.teacher;

import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;
import com.alibaba.excel.EasyExcel;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import org.springframework.web.multipart.MultipartFile;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.ao.controller.admin.teacher.vo.*;
import cn.iocoder.yudao.module.ao.dal.dataobject.teacher.TeacherDO;
import cn.iocoder.yudao.module.ao.service.teacher.TeacherService;

@Tag(name = "管理后台 - 教师信息")
@RestController
@RequestMapping("/ao/teacher")
@Validated
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    @PostMapping("/create")
    @Operation(summary = "创建教师信息")
    @PreAuthorize("@ss.hasPermission('ao:teacher:create')")
    public CommonResult<Long> createTeacher(@Valid @RequestBody TeacherSaveReqVO createReqVO) {
        return success(teacherService.createTeacher(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新教师信息")
    @PreAuthorize("@ss.hasPermission('ao:teacher:update')")
    public CommonResult<Boolean> updateTeacher(@Valid @RequestBody TeacherSaveReqVO updateReqVO) {
        teacherService.updateTeacher(updateReqVO);
        return success(true);
    }

    // 删除功能已移除，防止误删重要的教师基础数据
    // @DeleteMapping("/delete")
    // @Operation(summary = "删除教师信息")
    // @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('ao:teacher:delete')")
    // public CommonResult<Boolean> deleteTeacher(@RequestParam("id") Long id) {
    //     teacherService.deleteTeacher(id);
    //     return success(true);
    // }

    // @DeleteMapping("/delete-list")
    // @Parameter(name = "ids", description = "编号", required = true)
    // @Operation(summary = "批量删除教师信息")
    // @PreAuthorize("@ss.hasPermission('ao:teacher:delete')")
    // public CommonResult<Boolean> deleteTeacherList(@RequestParam("ids") List<Long> ids) {
    //     teacherService.deleteTeacherListByIds(ids);
    //     return success(true);
    // }

    @GetMapping("/get")
    @Operation(summary = "获得教师信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ao:teacher:query')")
    public CommonResult<TeacherRespVO> getTeacher(@RequestParam("id") Long id) {
        TeacherDO teacher = teacherService.getTeacher(id);
        return success(BeanUtils.toBean(teacher, TeacherRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得教师信息分页")
    @PreAuthorize("@ss.hasPermission('ao:teacher:query')")
    public CommonResult<PageResult<TeacherRespVO>> getTeacherPage(@Valid TeacherPageReqVO pageReqVO) {
        PageResult<TeacherDO> pageResult = teacherService.getTeacherPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, TeacherRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出教师信息 Excel")
    @PreAuthorize("@ss.hasPermission('ao:teacher:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTeacherExcel(@Valid TeacherPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TeacherDO> list = teacherService.getTeacherPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "教师信息.xls", "数据", TeacherRespVO.class,
                        BeanUtils.toBean(list, TeacherRespVO.class));
    }

    @GetMapping("/schedule")
    @Operation(summary = "获取教师课程表")
    @Parameter(name = "teacherId", description = "教师ID", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ao:teacher:query')")
    public CommonResult<Map<String, Object>> getTeacherSchedule(@RequestParam("teacherId") Long teacherId) {
        Map<String, Object> schedule = teacherService.getTeacherSchedule(teacherId);
        return success(schedule);
    }

    @GetMapping("/get-import-template")
    @Operation(summary = "获得导入教师信息模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手工创建导入模板的数据
        List<TeacherImportExcelVO> list = Arrays.asList(
                TeacherImportExcelVO.builder()
                        .serialNumber("1")
                        .deptName("计算机学院")
                        .teacherName("张三")
                        .teacherNo("T001")
                        .position("教师")
                        .genderStr("男")
                        .ageStr("30")
                        .maritalStatusStr("已婚")
                        .ethnicity("汉族")
                        .idCard("123456789012345678")
                        .birthDateStr("1990年5月15日")
                        .contactPhone("13800138000")
                        .entryDateStr("2020-09-01")
                        .entryYearStr("2020")
                        .entryMonthStr("9")
                        .serviceYearsStr("3.5")
                        .educationLevel("本科")
                        .major("计算机科学与技术")
                        .graduateSchool("某某大学")
                        .certificateIssueDateStr("2019-06-30")
                        .contractSignDateStr("2020-09-01")
                        .contractExpireDateStr("2025-08-31")
                        .graduationDateStr("2012-07-01")
                        .professionalTitle("讲师")
                        .build()
        );
        // 输出
        ExcelUtils.write(response, "教师信息导入模板.xls", "教师信息", TeacherImportExcelVO.class, list);
    }

    @PostMapping("/import")
    @Operation(summary = "导入教师信息")
    @Parameter(name = "file", description = "Excel 文件", required = true)
    @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    @PreAuthorize("@ss.hasPermission('ao:teacher:import')")
    public CommonResult<TeacherImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                         @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {

        // 简化的文件信息日志
        System.out.println("=== 开始导入Excel文件 ===");
        System.out.println("文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + String.format("%.2f KB", file.getSize() / 1024.0));

        // 直接使用原始数据创建TeacherImportExcelVO对象
        List<TeacherImportExcelVO> list = new ArrayList<>();

        try {
            List<Map<Integer, String>> rawData = EasyExcel.read(file.getInputStream()).doReadAllSync();
            System.out.println("成功读取 " + rawData.size() + " 条记录");

            for (int i = 0; i < rawData.size(); i++) {
                Map<Integer, String> row = rawData.get(i);
                TeacherImportExcelVO teacher = new TeacherImportExcelVO();

                // 手动映射每个字段
                teacher.setSerialNumber(row.get(0));
                teacher.setDeptName(row.get(1));
                teacher.setTeacherName(row.get(2));
                teacher.setTeacherNo(row.get(3));
                teacher.setPosition(row.get(4));
                teacher.setGenderStr(row.get(5));
                teacher.setAgeStr(row.get(6));
                teacher.setMaritalStatusStr(row.get(7));
                teacher.setEthnicity(row.get(8));
                teacher.setIdCard(row.get(9));
                teacher.setBirthDateStr(row.get(10));
                teacher.setContactPhone(row.get(11));
                teacher.setEntryDateStr(row.get(12));
                teacher.setEntryYearStr(row.get(13));
                teacher.setEntryMonthStr(row.get(14));
                teacher.setServiceYearsStr(row.get(15));
                teacher.setHouseholdType(row.get(16));
                teacher.setNativePlace(row.get(17));
                teacher.setHouseholdAddress(row.get(18));
                teacher.setCurrentAddress(row.get(19));
                teacher.setEducationLevel(row.get(20));
                teacher.setMajor(row.get(21));
                teacher.setGraduateSchool(row.get(22));
                teacher.setProfessionalCertificate(row.get(23));
                teacher.setTeachingCertificateNo(row.get(24));
                teacher.setCertificateIssuer(row.get(25));
                teacher.setCertificateIssueDateStr(row.get(26));
                teacher.setContractCountStr(row.get(27));
                teacher.setContractSignDateStr(row.get(28));
                teacher.setContractExpireDateStr(row.get(29));
                teacher.setSocialInsurance(row.get(30));
                teacher.setEmergencyContact(row.get(31));
                teacher.setPersonalEmail(row.get(32));
                teacher.setQqNumber(row.get(33));
                teacher.setPoliticalStatus(row.get(34));
                teacher.setPersonnelChanges(row.get(35));
                teacher.setHobbiesSpecialties(row.get(36));
                teacher.setGraduationDateStr(row.get(37));
                teacher.setProfessionalLevel(row.get(38));
                teacher.setProfessionalTitle(row.get(39));

                list.add(teacher);
            }

            // 只显示第一条记录作为示例
            if (!list.isEmpty()) {
                TeacherImportExcelVO firstTeacher = list.get(0);
                System.out.println("=== 数据示例（第1条记录）===");
                System.out.println("姓名: " + firstTeacher.getTeacherName() +
                                 ", 部门: " + firstTeacher.getDeptName() +
                                 ", 工号: " + firstTeacher.getTeacherNo());
            }
        } catch (Exception e) {
            System.out.println("Excel读取失败: " + e.getMessage());
            // 如果手动映射失败，回退到原来的方式
            list = ExcelUtils.read(file, TeacherImportExcelVO.class);
        }

        // 简化的导入信息
        System.out.println("=== 准备导入 " + list.size() + " 条教师记录 ===");
        return success(teacherService.importTeacherList(list, updateSupport));
    }

    @GetMapping("/simple-list")
    @Operation(summary = "获得教师简单列表")
    @PreAuthorize("@ss.hasPermission('ao:teacher:query')")
    public CommonResult<List<TeacherRespVO>> getSimpleTeacherList() {
        List<TeacherDO> list = teacherService.getSimpleTeacherList();
        return success(BeanUtils.toBean(list, TeacherRespVO.class));
    }

}